/**
 * 
 */
package stc.skymobi.distributed;

import java.io.IOException;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;

import stc.skymobi.ebus.EventBus;


/**
 * @author hp
 *
 */
public class ZooKeeperWrapper {
	
	private	ZooKeeper	zk;
	private	String		connectString;
	private	int 		sessionTimeout;
	private	String		eventZooKeeperStateChanged;
	private	EventBus	eventBus;
	private	KeeperState	lastState = null;
	
	/**
	 * @return the eventZooKeeperStateChanged
	 */
	public String getEventZooKeeperStateChanged() {
		return eventZooKeeperStateChanged;
	}
	/**
	 * @param eventZooKeeperStateChanged the eventZooKeeperStateChanged to set
	 */
	public void setEventZooKeeperStateChanged(String eventZooKeeperStateChanged) {
		this.eventZooKeeperStateChanged = eventZooKeeperStateChanged;
	}
	/**
	 * @return the connectString
	 */
	public String getConnectString() {
		return connectString;
	}
	/**
	 * @param connectString the connectString to set
	 */
	public void setConnectString(String connectString) {
		this.connectString = connectString;
	}
	/**
	 * @return the sessionTimeout
	 */
	public int getSessionTimeout() {
		return sessionTimeout;
	}
	/**
	 * @param sessionTimeout the sessionTimeout to set
	 */
	public void setSessionTimeout(int sessionTimeout) {
		this.sessionTimeout = sessionTimeout;
	}
	
	public void start() throws IOException {
		zk = new ZooKeeper(connectString, sessionTimeout, new Watcher(){

			public void process(WatchedEvent event) {
				if ( event.getType().equals(EventType.None) ) {
					System.out.println(event);
					
					if ( lastState == null || !lastState.equals(event.getState())) {
						lastState = event.getState();
						fireZooKeeperState();
					}
				}
			}} );
	}
	
	public void stop() throws InterruptedException {
		zk.close();
	}

	public void	fireZooKeeperState() {
		eventBus.fireEvent(eventZooKeeperStateChanged, zk, lastState );
	}
	/**
	 * @return the eventBus
	 */
	public EventBus getEventBus() {
		return eventBus;
	}
	/**
	 * @param eventBus the eventBus to set
	 */
	public void setEventBus(EventBus eventBus) {
		this.eventBus = eventBus;
	}
}
